package com.kintreda.service.platform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kintreda.common.config.R;
import com.kintreda.common.config.exception.CommonBaseErrorCode;
import com.kintreda.common.config.exception.CommonBaseException;
import com.kintreda.common.mybatis.entity.SysTask;
import com.kintreda.common.mybatis.model.BasePageModel;
import com.kintreda.common.mybatis.service.ISysTaskService;
import com.kintreda.common.oauth.annotation.SetLog;
import com.kintreda.service.sysjob.task.CronTaskRegistrar;
import com.kintreda.service.sysjob.task.SchedulingRunnable;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/platform/task")
@Api(tags = "任务接口")
public class TaskController {

    @Autowired
    private ISysTaskService iTaskService;
    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;

    @ApiOperation(value = "任务列表")
    @GetMapping("/list")
    public R<IPage<SysTask>> list(BasePageModel param){
        IPage<SysTask> result = iTaskService.getList(param);
        return R.ok(result);
    }

    @ApiOperation(value = "添加任务")
    @PostMapping("/save")
    @SetLog("添加或修改定时任务")
    public R<Boolean> doSave(@Valid @RequestBody SysTask param){
        //不能修改Bean名称和method名称
        if (ObjectUtils.isNotEmpty(param.getTaskId()) && param.getTaskId()>0){
            SysTask oldTask = iTaskService.getById(param.getTaskId());
            param.setBeanName(oldTask.getBeanName());
            param.setMethodName(oldTask.getMethodName());
        }
        SchedulingRunnable task = new SchedulingRunnable(param.getBeanName(), param.getMethodName(), param.getMethodParams());
        if (!task.isOk()){
            throw new CommonBaseException(CommonBaseErrorCode.SYS_ERROR.setErrMsg("任务Bean不存在或方法不存在!"));
        }
        try {
            param.setCreateTime(LocalDateTime.now());
            param.setUpdateTime(LocalDateTime.now());
            iTaskService.saveOrUpdate(param);
            //先停掉
            cronTaskRegistrar.removeCronTask(task);
            //启用
            if (param.getStatus().equals(1)){
                cronTaskRegistrar.addCronTask(task,param.getCronExpression());
            }
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            throw new CommonBaseException(CommonBaseErrorCode.SYS_ERROR);
        }
    }

    @ApiOperation(value = "开始任务")
    @PutMapping("/start/{taskId}")
    @SetLog("启动定时任务")
    public R<Boolean> start(@PathVariable Integer taskId){
        SysTask taskInfo = iTaskService.getById(taskId);
        if (ObjectUtils.isEmpty(taskInfo) ){
            throw new CommonBaseException(CommonBaseErrorCode.DATA_IS_NULL);
        }
        try {
            SchedulingRunnable task = new SchedulingRunnable(taskInfo.getBeanName(), taskInfo.getMethodName(), taskInfo.getMethodParams());
            cronTaskRegistrar.addCronTask(task,taskInfo.getCronExpression());
            taskInfo.setUpdateTime(LocalDateTime.now());
            taskInfo.setStatus(1);
            iTaskService.updateById(taskInfo);
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            throw new CommonBaseException(CommonBaseErrorCode.SYS_ERROR);
        }
    }

    @ApiOperation(value = "停止任务")
    @PutMapping("/stop/{taskId}")
    @SetLog("停止定时任务")
    public R<Boolean> stop(@PathVariable Integer taskId){
        SysTask taskInfo = iTaskService.getById(taskId);
        if (ObjectUtils.isEmpty(taskInfo) ){
            throw new CommonBaseException(CommonBaseErrorCode.DATA_IS_NULL);
        }
        try {
            SchedulingRunnable task = new SchedulingRunnable(taskInfo.getBeanName(), taskInfo.getMethodName(), taskInfo.getMethodParams());
            cronTaskRegistrar.removeCronTask(task);
            taskInfo.setStatus(0);
            iTaskService.updateById(taskInfo);
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            throw new CommonBaseException(CommonBaseErrorCode.SYS_ERROR);
        }
    }

    @ApiOperation(value = "删除任务")
    @DeleteMapping("/del/{taskId}")
    @SetLog("删除定时任务")
    public R<Boolean> del(@PathVariable Integer taskId){
        SysTask taskInfo = iTaskService.getById(taskId);
        if (ObjectUtils.isEmpty(taskInfo) ){
            throw new CommonBaseException(CommonBaseErrorCode.DATA_IS_NULL);
        }
        try {
            SchedulingRunnable task = new SchedulingRunnable(taskInfo.getBeanName(), taskInfo.getMethodName(), taskInfo.getMethodParams());
            cronTaskRegistrar.removeCronTask(task);
            iTaskService.removeById(taskId);
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            throw new CommonBaseException(CommonBaseErrorCode.SYS_ERROR);
        }
    }



}
